<template>
	<view class="container">
		<!-- 海报预览 -->
		<view class="preview-box">
			<image v-if="posterUrl" :src="posterUrl" class="preview-image" mode="widthFix" />
			<view v-else class="loading">生成海报中...</view>
		</view>

		<!-- 操作按钮 -->
		<div class="btn_box">
			<div class="back">返回</div>
			<div @tap="handleSave" class="save">保存到相册</div>
		</div>

		<!-- 隐藏的画布 -->
		<canvas canvas-id="posterCanvas" :style="canvasStyle" />
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted
	} from 'vue';
	import sheep from '@/sheep';

	// 画布配置
	const canvasWidth = 1020;
	const canvasHeight = 1814;
	const canvasStyle = ref({
		width: `${canvasWidth}px`,
		height: `${canvasHeight}px`,
		position: 'fixed',
		left: '-9999px',
	});
	let shop_name = '';
	// 图片资源
	const posterUrl = ref('');
	const QRcodeTool = 'https://pageandy.liuliangbenben.top/qrcode/build?text='
	const mpUrl = 'https://shisan-xi.work'
	const bgImage =
		'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/sjrz/20250322/3ca9e3500058875d72d1d4ea8a316a1f.png';
	const qrImage =
		'https://xyh-static-app.oss-cn-hangzhou.aliyuncs.com/storage/sjrz/20250319/9a967f74bdc9300cd25210ef86a4ea4e.png';

	// 初始化绘制
	onMounted(async () => {
		await getShopList()
		if(shop_name){
			const ctx = uni.createCanvasContext('posterCanvas');
			await drawPoster(ctx);
			await generatePreview();
		}
	});

	function getQrUrl() {
		return QRcodeTool + encodeURIComponent(mpUrl + '?shop_name=' + shop_name)
	}
	// 绘制海报
	// 修改图片加载逻辑
	const loadImage = (src) => {
		return new Promise((resolve) => {
			uni.getImageInfo({
				src,
				success: (res) => {
					// console.log('图片加载成功:', src, res);
					resolve(res);
				},
				fail: (err) => {
					console.error('图片加载失败:', src, err);
					uni.showToast({
						title: '资源加载失败',
						icon: 'error'
					});
					resolve(null); // 添加失败处理
				},
			});
		});
	};

	// 修改绘制逻辑
	const drawPoster = async (ctx) => {
		const {
			error,
			data
		} = await sheep.$api.user.org.getCode()

		console.log(data);
		//  getQrUrl() data.path
		// 加载图片资源
		const [bg, qr] = await Promise.all([loadImage(bgImage), loadImage(getQrUrl())]);

		// 增加资源校验
		if (!bg || !qr) {
			uni.showToast({
				title: '图片资源加载失败',
				icon: 'error'
			});
			return;
		}

		// 清空画布
		ctx.clearRect(0, 0, canvasWidth, canvasHeight);

		// 绘制背景
		ctx.drawImage(bg.path, 0, 0, canvasWidth, canvasHeight);

		// 绘制二维码（调整位置和尺寸）
		const qrSize = 500; // 二维码尺寸
		const qrX = (canvasWidth - qrSize) / 2; // 水平居中
		const qrY = 700; // 垂直位置

		// 去除二维码边框（根据实际边框宽度调整）
		const borderWidth = 8;
		ctx.drawImage(
			qr.path,
			borderWidth,
			borderWidth,
			qr.width - borderWidth * 2,
			qr.height - borderWidth * 2,
			qrX,
			qrY,
			qrSize,
			qrSize,
		);

		const fontSize = 50
		ctx.setFontSize(fontSize)
		// 绘制店名白底
		const metrics = ctx.measureText(shop_name)
		const textX = (canvasWidth - metrics.width) / 2
		const textY = qrY + borderWidth * 2 + qrSize + fontSize / 2
		ctx.setFillStyle('#ffffff')
		ctx.fillRect(qrX, (qrY + qrSize), qrSize, (fontSize + 20))
		// 绘制店名
		ctx.setFillStyle('#333333')
		ctx.fillText(shop_name, textX, textY, qrSize)

		// 执行绘制
		ctx.draw(true); // 改为同步绘制
	};

	// 修改生成预览逻辑
	const generatePreview = async () => {
		// 增加延时确保绘制完成
		await new Promise((resolve) => setTimeout(resolve, 500));

		const res = await new Promise((resolve) => {
			uni.canvasToTempFilePath({
				canvasId: 'posterCanvas',
				success: (result) => {
					// console.log('生成预览图:', result);
					resolve(result);
				},
				fail: (err) => {
					console.error('生成预览图失败:', err);
					resolve(null);
				},
			});
		});

		if (res && res.tempFilePath) {
			posterUrl.value = res.tempFilePath;
		} else {
			uni.showToast({
				title: '海报生成失败',
				icon: 'error'
			});
		}
	};
	async function getShopList(){
		let {data,error,msg} = await sheep.$api.user.getShopList()
		if(error == 0){
			shop_name = data[0].name
		}else  {
			uni.showModal({
				title:'提示',
				content:msg,
				showCancel:false,
				success:  (res)=>{
					if (res.confirm) {
						const hasHistory = sheep.$router.hasHistory();
						if (hasHistory) {
						  sheep.$router.back();
						} else {
						  sheep.$router.go('/pages/index/home');
						}
					}  
				}
			})
		}
	}
	// 保存图片
	const handleSave = async () => {
		console.log(posterUrl.value);

		try {
			await uni.saveImageToPhotosAlbum({
				filePath: posterUrl.value,
			});
			uni.showToast({
				title: '保存成功'
			});
		} catch (err) {
			uni.showToast({
				title: '保存失败',
				icon: 'error'
			});
		}
	};
</script>

<style lang="less" scoped>
	.container {
		padding: 40rpx;
		min-height: 100vh;
		background: #f7f7f7;
	}

	.preview-box {
		//   background: #000000;
		border-radius: 20rpx;
		padding: 20rpx;
		margin-bottom: 40rpx;

		.preview-image {
			width: 100%;
			border-radius: 16rpx;
		}

		.loading {
			height: 800rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #999;
		}
	}

	.btn_box {
		box-sizing: border-box;
		width: 100%;
		height: 100rpx;
		display: flex;
		padding: 15rpx;
		justify-content: space-between;
		align-items: center;
		// background-color: #000000;

		.save,
		.back {
			width: 260rpx;
			height: 80rpx;
			text-align: center;
			line-height: 80rpx;
			color: #000000;
			border-radius: 44rpx;
			font-size: 28rpx;
		}

		.back {
			box-sizing: border-box;
			border: 1px solid #d8d8d8;
		}

		.save {
			color: #fff;
			background: linear-gradient(270deg, #003ad9 0%, #3dc8ff 100%);
		}
	}
</style>